/*
 * Copyright (c) 2024-2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const fs = require('fs')

function camelCasePath(path) {
  return path
    .replace(/[\/_]/g, ' ') 
    .split(' ')
    .map(part => part.charAt(0).toUpperCase() + part.slice(1))
    .join('')
}

function generateTsFile(jsonFile, outputFile) {
  const data = JSON.parse(fs.readFileSync(jsonFile, 'utf8'))
  const imports = []
  const registrations = []
  for (const path of data.src ?? []) {
    const alias = camelCasePath(path)
    const importLine = `import {__EntryWrapper as ${alias} } from '../${path}'`
    imports.push(importLine)
    const registrationLine = `  registerPage('${path}', Type.from<${alias}>().getName())`
    registrations.push(registrationLine)
  }

  const header = 'import { registerPage } from "@ohos.router"'
  const funcStart = '\nexport function pageRegistration() {'
  const funcEnd = '}'
  const result = [
    header,
    ...imports,
    '',
    funcStart,
    registrations.join('\n'),
    funcEnd
  ].join('\n')
  fs.writeFileSync(outputFile, result, 'utf8')
  console.info(`Created file: ${outputFile}`)
}

generateTsFile('../entry/src/main/resources/base/profile/main_pages.json',
  '../entry/src/main/ets/entryability/PageRegistration.ets')
